<template>
  <ConfigProvider>
    <div class="login-container" :style="styles">
      <Form
        class="login-form"
        ref="formRef"
        :rules="rules"
        :model="formState"
        layout="vertical"
        hideRequiredMark
      >
        <h3 v-if="title" class="title-wrap">
          {{ title }}
        </h3>
        <div class="login-title">登录</div>
        <FormItem class="mb-6" label="" name="username">
          <Input
            v-model:value="formState.username"
            placeholder="账号"
            allow-clear
          >
            <template #prefix
              ><img
                src="/static/custom-login/user-icon.png"
                class="h-[16px] w-[16px]"
            /></template>
          </Input>
        </FormItem>
        <FormItem class="mb-4" name="password">
          <InputPassword
            v-model:value="formState.password"
            placeholder="密码"
            @keyup.enter="handleLogin"
            allow-clear
          >
            <template #prefix
              ><img
                src="/static/custom-login/password-icon.png"
                class="h-[16px] w-[16px]"
            /></template>
          </InputPassword>
        </FormItem>
        <FormItem name="code" v-if="needCaptcha">
          <Flex>
            <Input
              v-model:value="formState.code"
              placeholder="验证码"
              @keyup.enter="handleLogin"
            ></Input>
            <img
              class="captcha-image ml-2 h-10 rounded-sm"
              :src="captcha"
              @click="refreshCode"
            />
          </Flex>
        </FormItem>
        <FormItem class="mb-8">
          <Checkbox v-model:checked="formState.rememberMe">
            <span class="remember-password">记住密码</span>
          </Checkbox>
        </FormItem>
        <FormItem>
          <Button class="login-btn" @click="handleLogin" :loading="loading"
            >登录</Button
          >
        </FormItem>
      </Form>
    </div>
  </ConfigProvider>
</template>

<route lang="json">
{
  "name": "custom-login",
  "meta": {
    "layout": false,
    "hideInTabs": true
  }
}
</route>

<script setup lang="ts">
import { CSSProperties, computed, onMounted, ref } from 'vue';
import { useThemeState } from '@/layout/store/useThemeStore';
import { useTabViewsStore, useUserStore } from '@boeyo/portal';
import {
  Button,
  Checkbox,
  Flex,
  Form,
  FormInstance,
  FormItem,
  FormProps,
  Input,
  InputPassword,
} from 'ant-design-vue';
import { ConfigProvider } from 'ant-design-vue';
import Cookie from 'js-cookie';
import { useRequest } from 'vue-request';
import { useRoute, useRouter } from 'vue-router';
import { fetchCodeImageApi, toLogin } from './api';

const { styles } = useThemeState();

const route = useRoute();

const router = useRouter();

const USER_NAME_KEY = 'ACCOUNT';
const PASSWORD_KEY = 'ACCOUNT_SECRET';
const CHECK_EXPIRE_KEY = 'CHECK_EXPIRE';

interface LoginState {
  username: string;
  password: string;
  rememberMe: boolean;
  code: string;
  uuid: string;
}

const formRef = ref<FormInstance>();
const formState = ref<LoginState>({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
});

const checkExpire = ref('');

const rules: FormProps['rules'] = {
  username: [{ trigger: 'blur', required: true, message: '请输入用户名' }],
  password: [{ trigger: 'blur', required: true, message: '请输入密码' }],
  code: [{ trigger: 'blur', required: true, message: '请输入验证码' }],
};

const title = '智能监控平台';

const tabViewsStore = useTabViewsStore();

onMounted(() => {
  tabViewsStore.closeAllTab();
  const username = Cookie.get(USER_NAME_KEY);
  const password = Cookie.get(PASSWORD_KEY);
  checkExpire.value = Cookie.get(CHECK_EXPIRE_KEY) || true;
  if (username && password) {
    formState.value = {
      ...formState.value,
      username,
      password: atob(password),
      rememberMe: true,
    };
  }
});

const { run: login, loading } = useRequest(toLogin, {
  manual: true,
  onSuccess(result) {
    if (result.token) {
      useUserStore().setToken(result.token);
    }
    console.log('登录成功', route.query.redirect);
    router.push({ path: (route.query.redirect as string) || '/main-nav' });
  },
});

const handleLogin = async () => {
  const result = await formRef.value?.validate();

  if (formState.value.rememberMe) {
    const { username, password } = formState.value;
    Cookie.set(USER_NAME_KEY, username);
    Cookie.set(PASSWORD_KEY, btoa(password));
  }
  if (!result) return;
  login({
    ...formState.value,
    checkExpire: checkExpire.value,
  });
};

const needCaptcha = ref(false);
const captcha = ref('');

const refreshCode = () => {
  fetchCodeImageApi().then((res) => {
    needCaptcha.value = (res as any).captchaEnabled ?? true;
    if (needCaptcha.value) {
      captcha.value = `data:image/gif;base64,${(res as any).img}`;
      formState.value.uuid = (res as any).uuid;
    }
  });
};

refreshCode();

const style = computed<CSSProperties>(() => {
  return {
    // backgroundImage: `url(${commonStore.loginBgUrl})`,
  };
});
</script>

<style lang="scss" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  position: relative;
  background: url('/static/custom-login/login-bg-2.png');
  background-size: 100% 100%;
}

.login-form {
  position: absolute;
  left: 65%;
  top: 50%;
  // transform: translateX(-12%) translateY(-50%);
  transform: translateY(-50%);
  width: 428px;
  padding: 42px 54px 24px;
  box-shadow: 0 0 40px #08071099;
  background: linear-gradient(270deg, #1d252f 0%, #3e4c5c 100%);
  border-radius: 8px;
}

.captcha-image {
  height: 40px;
  margin-left: 8px;
  border-radius: 2px;
}

.remember-password {
  color: #fff;
}

.login-btn {
  width: 320px;
  height: 48px;
  background: linear-gradient(90deg, #4fd1f5 0%, #0f404d 100%);
  border-radius: 6px 6px 6px 6px;
  border: none;
  color: #fff;
  font-size: 18px;
}

.title-wrap {
  color: #fff;
  font-size: 32px;
  font-weight: 600;
  text-align: center;
  margin: 0 auto 20px;
}

.login-title {
  width: 36px;
  height: 18px;
  font-weight: 500;
  font-size: 18px;
  color: #ffffff;
  line-height: 18px;
  text-align: left;
  margin-bottom: 18px;
}

.custom-select {
  :deep(.ant-select-selector) {
    padding-left: 10%;
  }
  :deep(.ant-select-arrow) {
    left: 4%;
    font-size: 14px;
    // color: #333;
  }
}
</style>
